
#include "lib_bmp.h"

//*******************************************************************************


//*******************************************************************************

int bmp_gen_file(char *fileName, uint32_t width, uint32_t height, uint32_t color,uint8_t * buff)
{
    FILE *fp;
    uint32_t i, j;
    LITTLE l_width, l_height, l_bfSize, l_biSizeImage;

    uint8_t r = 0;//color >> 16;
    uint8_t g = 0;//color >> 8;
    uint8_t b = 0;//color;
    uint8_t a = 0;//color;
    uint32_t width_r  =  (width * 24 / 8 + 3) / 4 * 4;
    uint32_t bfSize = width_r * height + 54 + 2;
    uint32_t biSizeImage = width_r * height;

    l_width.value = width;
    l_height.value = height;
    l_bfSize.value = bfSize;
    l_biSizeImage.value = biSizeImage;

    /* BMP file format: www.cnblogs.com/wainiwann/p/7086844.html */
    uint8_t bmp_head_map[54] = {
        /* bmp file header: 14 byte */
        0x42, 0x4d,
        // bmp pixel size: width * height * 3 + 54
        l_bfSize.bytes[0], l_bfSize.bytes[1], l_bfSize.bytes[2], l_bfSize.bytes[3],
        0, 0 , 0, 0,
        54, 0 , 0, 0,    /* 14+40=54 */

        /* bmp map info: 40 byte */
        40, 0, 0, 0,
        //width
        l_width.bytes[0], l_width.bytes[1], l_width.bytes[2], l_width.bytes[3],
        //height
        l_height.bytes[0], l_height.bytes[1], l_height.bytes[2], l_height.bytes[3],
        1, 0,
        24, 00,             /* 24 bit: R[8]/G[8]/B[8] */

        0, 0, 0, 0,     //biCompression:0
//        0, 0, 0, 0,     //biSizeImage：A2 00 00 00=162
        l_biSizeImage.bytes[0], l_biSizeImage.bytes[1], l_biSizeImage.bytes[2], l_biSizeImage.bytes[3],
        0, 0, 0, 0,     //biXPelsPerMeter: 60 0F 00 00
        0, 0, 0, 0,     //biYPelsPerMeter
        0, 0, 0, 0,     //biClrUsed
        0, 0, 0, 0      //biClrImportant
    };

    /* write in binary format */
    fp = fopen(fileName, "wb+");
    if(fp == NULL){
        log_e("%s: file create failed!\n", fileName);
        return -1;
    }

    log_d("%s: file create success!\n", fileName);

    fwrite(bmp_head_map, sizeof(bmp_head_map), 1, fp);

    for(i = 0; i < height; i++) {
        for(j = 0; j < width; j++)
        {
			//RK_FORMAT_BGRA_8888
			#if 0
			b = 255;//*(buff+0);
			g = 26;//*(buff+1);
			r = 0;//*(buff+2);
			a = 0;//*(buff+3);
			//buff = buff + 4;	
			#elif 1
			b = *(buff+0);
			g = *(buff+1);
			r = *(buff+2);
			a = *(buff+3);
			buff = buff + 4;
			#endif
            fprintf(fp, "%c%c%c", b, g, r); /* BGR */
		}
    	//4 byte align
        for(j = 0; j < width_r-width*3; j++)
            fprintf(fp, "%c", 0);
    }

    if(fclose(fp)){
        log_e("file close failed!\n");
        return -1;
    }
    fp = NULL;

    log_d("width: %d\n", width);
    log_d("height: %d\n", height);    
    log_d("write ok\n");

    return 0;
}














